package com.zone.vehicle.lib.view.textview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.TextView;

/**
 * @Author: pkqlqx
 * @CreateDate: 2022/1/11 11:38
 * @Description:
 */
@SuppressLint("AppCompatCustomView")
public class ExpandableTextView extends TextView {

    // 最大行，默认显示1行
    private final int MAX = 1;
    // 完全展开需要的行数
    private int lines;

    private ExpandableTextView mExpandableTextView;

    private boolean expandablestatus = false;

    // 构造方法用两个参数的
    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mExpandableTextView = this;
        init();

    }

    private void init() {
        // 在view绘制之前的时候执行，在onDraw之前
        ViewTreeObserver mViewTreeObserver = this.getViewTreeObserver();
        mViewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                // 避免重复监听
                mExpandableTextView.getViewTreeObserver().removeOnPreDrawListener(this);
                // 获得内容行数
                lines = getLineCount();
                return true;
            }
        });
        setExpandable(false);

    }
    // 是否展开或者收缩，
    // true，展开；
    // false，不展开

    public void setExpandable(boolean isExpand) {
        if (isExpand) {
            setMaxLines(lines + 10);
        } else {
            setMaxLines(MAX);
        }
        expandablestatus = isExpand;
    }

    public boolean getExpandableStatus() {
        return expandablestatus;
    }

}
